import request from '@/utils/request'
import qs from 'qs';

// 通用POST方法
function post(route, params) {
  // console.log('登录的sessionID',sessionStorage.getItem("sessionId"))
  // 使用qs转换param对象变为url
  if (params) {
    params = qs.stringify(params);
  }

  let headers = {}
  if (/login/.test(route) == true) {
    headers = {
      'Content-Type': 'application/x-www-form-urlencoded',
    }
  } else {
    headers = {
      'Content-Type': 'application/x-www-form-urlencoded',
        // 'Authorization': sessionStorage.getItem("sessionId")
    }
  }

  return request({
      method: "POST",
      url: route,
      headers,
      data: params,
      // withCredentials: true
    })
};

/**
 * 上传文件专用，接受参数形式为formData
 */
function postUpload(method, root, url, params, success, failure, noLoad, credentials) {

  request({
      method: method,
      url: url,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      data: method === 'POST' || method === 'PUT' ? params : null,
      params: method === 'GET' || method === 'DELETE' ? params : null,
      baseURL: root,
      withCredentials: true
    })
    .then(function (res) {
      if (res) {
        if (success) {
          success(res);
        }
      } else {
        if (failure) {
          failure(res);
        } else {

        }
      }
    })
    .catch(function (err) {

      let res = err.response;
      if (err) {
        return;
      }
    });
}


export default {
  post,
  postUpload
}
